package com.frogs.ucenter.util.sms;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.SmsPartnerEnum;
import com.frogs.ucenter.dao.UserMessageSmsReceiverDao;
import com.frogs.ucenter.entity.SmsMessageMqEntity;
import com.frogs.ucenter.entity.UserMessageSmsLog;
import com.frogs.ucenter.entity.UserMessageSmsReceiver;
import com.frogs.ucenter.entity.UserMessageSmsLog.StatusEnum;

@Component("partnerSmsActiveMqSend")
public class PartnerSmsActiveMqSend {
	private static Logger log = LoggerFactory.getLogger(PartnerSmsActiveMqSend.class);
	@Resource(name="jmsTemplate")
    private JmsTemplate jmsTemplate;
	@Resource
	private UserMessageSmsReceiverDao userMessageSmsReceiverDao;
	@Resource
	private PartnerSmsQxHelper partnerSmsQxHelper;
	@Resource
	private PartnerSmsCFHelper partnerSmsCFHelper;
	@Resource
	private PartnerSmsLCHelper partnerSmsLCHelper;
	/**
	 * 发送到队列
	 * @param smsMessageMqEntity
	 */
	public void send(final SmsMessageMqEntity smsMessageMqEntity) {
		Session session = null;
		Connection connection = null;
		try {
			connection = jmsTemplate.getConnectionFactory().createConnection();//创建连接
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);//创建session
			String queueName = jmsTemplate.getDefaultDestinationName();//获取队列名
			Destination destination = session.createQueue(queueName);//创建队列
			Message message = session.createObjectMessage(smsMessageMqEntity);//创建发送内容
			session.createProducer(destination).send(message, DeliveryMode.PERSISTENT, smsMessageMqEntity.getLevel(), 5000000L);
		} catch (Exception e) {
			log.error("func[send] smsMessageMqEntity[" + smsMessageMqEntity + "] e["+e.getMessage()+"] desc[fail]");
		} finally {  
            try {  
                if (null != connection)  
                    connection.close();  
                if (null != session)  
                	session.close();  
            } catch (Throwable ignore) { 
            	log.error("func[send] ignore["+ignore.getMessage()+"] desc[fail]");
            }  
        }  
	}
	// 发送短信到运营商
	@Async
	public void sendToUser(SmsMessageMqEntity smsMessageMqEntity) {
		try{
			// 合作方判断
			String result = "";
			UserMessageSmsReceiver userMessageSmsReceiver = updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), StatusEnum.SEND_EXTRACT.getValue(), 0);//登记发送日志
			int id = userMessageSmsReceiver.getId();//userMessageSmsReceiver对应的主键id
			if (SmsPartnerEnum.QUAN_LI_TONG.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
				result = partnerSmsQxHelper.sendSms(smsMessageMqEntity);
			} else if (SmsPartnerEnum.BAI_FEN.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
				result = partnerSmsCFHelper.sendSms(smsMessageMqEntity);
			} else if (SmsPartnerEnum.LAN_CHUANG.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
				result = partnerSmsLCHelper.sendSms(smsMessageMqEntity);
			}
			this.returnDeal(result, smsMessageMqEntity, id);
		}catch(Exception e){
			log.error("func[sendToUser] e["+e.getMessage()+"] desc[fail]");
		}
	}
	
	/**
	 * 调用运营商返回结果处理
	 * @param result 运营商返回结果
	 */
	private void returnDeal(String result, SmsMessageMqEntity smsMessageMqEntity, int id){
		
		if(StringUtil.isEmpty(result)){//返回空，表示发送失败，更新原信息日志，继续重发
			this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_ERROR.getValue(), id);
			this.sendAgain(smsMessageMqEntity);
		}else{
			String resultDeal = result;
			Pattern p = null;
			Matcher m = null;
			if (SmsPartnerEnum.QUAN_LI_TONG.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
				p = Pattern.compile("<code>(.*?)</code>");
				m = p.matcher(resultDeal);
			} else if (SmsPartnerEnum.BAI_FEN.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
				p = Pattern.compile("<State>(.*?)</State>");
				m = p.matcher(resultDeal);
			}
			if (m.find()) {
				String code = m.group(1).trim();
				// 提交成功
				if (SmsPartnerEnum.QUAN_LI_TONG.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
					if (code.equals("00") || code.equals("03")) {
						this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_SUCCESS.getValue(), id);
					} else {
						this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_ERROR.getValue(), id);
						this.sendAgain(smsMessageMqEntity);
					}
				} else if (SmsPartnerEnum.BAI_FEN.getCode().equals(smsMessageMqEntity.getPartnerInterface())) {
					if (code.equals("0")) {
						this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_SUCCESS.getValue(), id);
					} else {
						this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_ERROR.getValue(), id);
						this.sendAgain(smsMessageMqEntity);
					}
				}
			} else {
				this.updateLog(smsMessageMqEntity.getId(), smsMessageMqEntity.getReceiver(), UserMessageSmsLog.StatusEnum.SEND_ERROR.getValue(), id);
				this.sendAgain(smsMessageMqEntity);
			}
		}
	}
	
	/**
	 * 登记发送日志
	 * @param logId
	 * @param receiver
	 * @param status
	 * @param id
	 * @return
	 */
	private UserMessageSmsReceiver updateLog(int logId, String receiver, int status, int id){
		UserMessageSmsReceiver userMessageSmsReceiver = null;
		if(UserMessageSmsLog.StatusEnum.SEND_EXTRACT.getValue() == status){//发送提起,插入一条新记录
			userMessageSmsReceiver = new UserMessageSmsReceiver();
			userMessageSmsReceiver.setLogId(logId);
			userMessageSmsReceiver.setReceiver(receiver);
			userMessageSmsReceiver.setStatus(status);
			userMessageSmsReceiver.setCreateTime(new Date());
			userMessageSmsReceiverDao.insert(userMessageSmsReceiver);
		}else{//更新记录
			userMessageSmsReceiver = userMessageSmsReceiverDao.selectById(id);
			userMessageSmsReceiver.setStatus(status);
			userMessageSmsReceiver.setFinishTime(new Date());
			userMessageSmsReceiverDao.update(userMessageSmsReceiver);
		}
		return userMessageSmsReceiver;
	}
	
	/**
	 * 重发接口
	 * @param smsMessageMqEntity
	 */
	private void sendAgain(SmsMessageMqEntity smsMessageMqEntity){
		int sendNum = smsMessageMqEntity.getSendNum();//重发次数，1表示已经重发，不再进行重发，否则重发
		int num = 1;//表示已经重发过，重发过则不再重发
		if(sendNum != num){//发送失败,进行重发
			smsMessageMqEntity.setSendNum(1);
			this.send(smsMessageMqEntity);
		}
	}
}
